import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  // if (route.meta && route.meta.roles) {
  //   return roles.some(role => route.meta.roles.includes(role))
  // } else {
  //   return true
  // }
  if (route.meta && route.meta.roles) {
    // console.log(route)
    return ['1'].some(role => role.includes(route.meta.is_menu))
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */

function generaMenu(routes, roles, parentRoute) {
  // console.log(roles)
  // console.log(parentRoute)
  roles.forEach(item => {
    // console.log(item)
    const menu = {
      path: `/${parentRoute}/${item.route}`,
      name: item.name,
      // component: Layout,
      meta: {
        title: `${item.name}`,
        icon: item.route,
        is_menu: item.is_menu,
        parent_id: item.parent_id,
        roles: ['admin'],
        name: item.name
      },
      children: [
        // {
        //   path: 'index',
        //   component: (resolve) => require([`@/views/${item.route}/index`], resolve),
        //   name: 'Icons',
        //   meta: {
        //     title: `${item.name}`,
        //     icon: 'icon', is_menu: item.is_menu,
        //     parent_id: item.parent_id === 0 ? item.parent_id : 'child'
        //   }
        // }
      ]
    }
    // if (item.childs) {
    if (!item.parent_id) {
      if (item.childs.length > 0) {
        menu.component = Layout
      }
      generaMenu(menu.children, item.childs, item.route)
    } else {
      menu.component = (resolve) => require([`@/views/${parentRoute}/${item.route}/index`], resolve)
    }
    routes.push(menu)
  })
  // console.log(routes)
}

export function filterAsyncRoutes(routes, roles) {
  // console.log(routes)
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    // console.log(tmp)
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    if (routes.length === 0) {
      asyncRoutes.length = 0
    }
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    // console.log(roles)
    return new Promise(resolve => {
      generaMenu(asyncRoutes, roles)
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
